package com.sample.logic;

import java.io.IOException;

import org.apache.commons.lang.SerializationUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import com.sample.constants.ServerConst;
import com.sample.info.InputInfo;
import com.sample.info.OutputInfo;
import com.sample.info.URLInfo;
import com.sample.util.Util;

/**
 * オブジェクト通信用ロジック
 * @author SASAKI
 *
 */
public class HttpSerializableSendLogic {

	/** URL(LocalTomcat) */
	private URLInfo urlInfo = new URLInfo(ServerConst.PROTCOL_HTTP, // http
											ServerConst.HOST_LOCAL, // 10.0.2.2
											ServerConst.PORT_8080, // Tomcat ListenPort
											ServerConst.APP_NAME, // Tomcat App Name
											ServerConst.SERIALIZE_SERVLET
											);
	/** 実機向け */
//	private URLInfo urlInfo = new URLInfo(ServerConst.PROTCOL_HTTP,
//			ServerConst.HOST_GAE,
//			null,
//			null,
//			ServerConst.STANDARD_SERVLET
//			);

	/**
	 * JavaObjectを送信する.
	 * @return 通信結果
	 */
	public String sendObject(InputInfo info) {

		HttpClient hc = new DefaultHttpClient();

		// URLにパラメータを付与
		StringBuffer sb = new StringBuffer(500);
		sb.append(urlInfo.toUrlString());

		HttpPost httpPost = new HttpPost(sb.toString());

		try {

			HttpEntity sendBody = new SerializableEntity(info, false);
			httpPost.setEntity(sendBody);

			// 送信
			HttpResponse res = hc.execute(httpPost);

			sb.append("\n");

			// 通信判定(正常:200,201)
			int status = res.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
				HttpEntity entity = res.getEntity();

				OutputInfo out = (OutputInfo) SerializationUtils.deserialize(entity.getContent());

				sb.append(info.toString());
				sb.append(out.toString());

			} else {
				sb.append("通信に失敗しました。\n");
				sb.append("StatusCode:" + status + "\n");
				sb.append("Reason    :" + res.getStatusLine().getReasonPhrase());
			}

		} catch (ClientProtocolException cpex) {
			sb.append(Util.getStackTraceString(cpex));
		} catch (IOException ioex) {
			sb.append(Util.getStackTraceString(ioex));
		}

		return sb.toString();
	}
}
